package cn.enjoy.boot.controller;

import cn.enjoy.tool.api.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.*;

/**
 * @author K
 * @date 2024-07-09 19:35
 */
@Slf4j
@RestController
@RequestMapping("queue")
public class QueueTestController {
    public static BlockingQueue<String> queue = new LinkedBlockingQueue<>();
    public static Executor threadPool = Executors.newFixedThreadPool(4);

    @GetMapping("put")
    public void put(String value) {
        queue.offer(value);
    }

    @GetMapping("put100")
    public void put(String value, int count) {
        for (int i = 0; i < count; i++) {
            queue.offer(value+i);
        }
    }

    @GetMapping("consume")
    public void consume() {
        threadPool.execute(() -> {
            while (true) {
                try {

                    String value = queue.poll(2000L, TimeUnit.MILLISECONDS);
                    if (value != null) {
                        log.info("出栈值：{}", value);
                    }
                    Thread.sleep(200L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @GetMapping("consumeOne")
    public R consumeOne() {
        try {
            String value = queue.poll(2000L, TimeUnit.MILLISECONDS);
            log.info("one出栈值：{}", value);
            return R.success(value);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return R.fail("失败");
    }

}
